package testing;

import java.net.UnknownHostException;
import java.util.List;

import common.messages.KVAdminMessage;
import common.messages.KVMessage;
import common.messages.MetaData;
import communicationLogic.ClientSocket;
import app_kvClient.KVClient;
import app_kvEcs.ECS;
import client.KVStore;
import junit.framework.TestCase;

public class ConnectionTest extends TestCase {
    
    private KVStore kvClient;
    Exception ex = null;
    KVMessage response = null;

    
    ECS ecs = new ECS("ECS.config");
    KVAdminMessage kvadmin = null;
    String ip = "";
    int port = 0;
    
    public void setUp() {
        ecs.initService(1);
        ecs.start();
        
        kvadmin = new KVAdminMessage();
        kvadmin.setMetaList(KVAdminMessage.sortMetaData(ecs.activeMap));
        
        List<MetaData> metaDatas = KVAdminMessage.sortMetaData(ecs.activeMap);
        for (MetaData m : metaDatas) {
            ip = m.getIp();
            port = Integer.parseInt(m.getPort());
        }
        
        kvClient = new KVStore(ip, port);
        try {
            kvClient.connect();
        } catch (Exception e) {
        }
    }

    public void tearDown() {
        kvClient.disconnect();
        ecs.stop();
        ecs.shutDown();
    }
    
    
    

    public void testConnectionSuccess() {
        
        List<MetaData> metaDatas = KVAdminMessage.sortMetaData(ecs.activeMap);
        for (MetaData m : metaDatas) {
            
            Exception ex = null;
            
            KVStore kvClient = new KVStore(m.getIp(), Integer.parseInt(m.getPort()));
            
            try {
                kvClient.connect();
            } catch (Exception e) {
                ex = e;
            }

            assertNull(ex);

        }
        

    }

    public void testUnknownHost() {
        Exception ex = null;
        KVStore kvClient = new KVStore("unknown", 50001);

        try {
            kvClient.connect();
        } catch (Exception e) {
            ex = e;
        }

        assertTrue(ex instanceof UnknownHostException);
    }

    public void testIllegalPort() {
        Exception ex = null;
        KVStore kvClient = new KVStore("localhost", 123456789);

        try {
            kvClient.connect();
        } catch (Exception e) {
            ex = e;
        }

        assertTrue(ex instanceof IllegalArgumentException);
    }

}
